<?php
class Pauler_Searchseo_Model_Mysql4_Query extends Mage_Core_Model_Mysql4_Abstract
{
  public function _construct(){
    $this->_init('searchseo/query','query_id');
  }
   /**
     * Retrieve select object for load object data
     *
     * @param   string $field
     * @param   mixed $value
     * @return  Zend_Db_Select
     */
    protected function _getLoadSelect($field, $value, $object)
    {
           $select = $this->_getReadAdapter()->select()
            ->from($this->getMainTable())
            ->where($this->getMainTable().'.'.$field.'=?', $value);
        return $select;
    }
   /**
     * Custom load model by search query string
     *
     * @param Mage_Core_Model_Abstract $object
     * @param string $value
     * @return Mage_CatalogSearch_Model_Mysql4_Query
     */
    public function loadByQuery(Mage_Core_Model_Abstract $object, $value)
    {
        $select = $this->_getReadAdapter()->select()
            ->from($this->getMainTable())
            ->where('query_text=?', $value)
            ->where('store_id=?', $object->getStoreId())
            ->order('query_text ASC')
            ->limit(1);
        if ($data = $this->_getReadAdapter()->fetchRow($select)) {
            $object->setData($data);
            $this->_afterLoad($object);
        }

        return $this;
    }

    /**
     * Custom load model only by query text (skip synonym for)
     *
     * @param Mage_Core_Model_Abstract $object
     * @param string $value
     * @return Mage_CatalogSearch_Model_Mysql4_Query
     */
    public function loadByQueryText(Mage_Core_Model_Abstract $object, $value)
    {
         $select = $this->_getReadAdapter()->select()
            ->from($this->getMainTable())
            ->where('query_text = ?', $value)
            ->where('store_id = ?', $object->getStoreId())
            ->limit(1);
        if ($data = $this->_getReadAdapter()->fetchRow($select)) {
            $object->setData($data);
            $this->_afterLoad($object);
        }
        return $this;
    }
    public function load(Mage_Core_Model_Abstract $object, $value, $field=null)
    {
        if (is_numeric($value)) {
            return parent::load($object, $value);
        }
        else {
            $this->loadByQuery($object,$value);
        }
        return $this;
    }

    public function _beforeSave(Mage_Core_Model_Abstract $object)
    {
        if(!$object->getId()){
            $object->setCreationTime($this->formatDate(Mage::getModel('core/date')->gmtTimestamp()));
        }
        $object->setUpdateTime($this->formatDate(Mage::getModel('core/date')->gmtTimestamp()));
        return $this;
    }

}
